#ifndef EVENT_LOOP_THREAD_H
#define EVENT_LOOP_THREAD_H

#include <pthread.h>
#include "Common.h"
#include "EventLoop.h"


// class EventLoop;

void *loopThreadRun(void *arg);

class EventLoopThread {

public:
	EventLoopThread();	

	int loopThreadInit(int ix) {
		pthread_mutex_init(&mutex_, NULL);
		pthread_cond_init(&cond_, NULL);
		loop_ = NULL;
		thread_count_ = 0;
		thread_tid_ = 0;

	    thread_name_ = "Thread-" + std::to_string((ix+1));
		
		return 0;
	}

	int loopThreadStart(int ix) {
	    // pthread_create(&thread_tid_, NULL, &loopThreadRun, this);
	    pthread_create(&thread_tid_, NULL, &loopThreadRun, this);

	    assert(pthread_mutex_lock(&mutex_) == 0);

    	while (loop_ == NULL) {
        	assert(pthread_cond_wait(&cond_, &mutex_) == 0);
    	}

    	assert(pthread_mutex_unlock(&mutex_) == 0);

        printf("event loop thread started, %s", thread_name_.c_str());
    	
    	return 0;
    	// return eventLoopThread->eventLoop;
	}

// private:
	// void *loopThreadRun(void) {

public:
// private:
    EventLoop *loop_;
    pthread_t thread_tid_;        /* thread ID */
    pthread_mutex_t mutex_;
    pthread_cond_t cond_;
    std::string thread_name_;
    long thread_count_;    /* # connections handled */
};


void *loopThreadRun(void *arg) {
    // struct event_loop_thread *eventLoopThread = (struct event_loop_thread *) arg;
    EventLoopThread *threadloop = (EventLoopThread *) arg;
    pthread_mutex_lock(&threadloop->mutex_);

    threadloop->loop_ = new EventLoop(threadloop->thread_name_);
    printf("event loop thread init and signal, %s", threadloop->thread_name_.c_str());

    pthread_cond_signal(&threadloop->cond_);

    pthread_mutex_unlock(&threadloop->mutex_);

    //子线程event loop run
    threadloop->loop_->run();

    // pthread_mutex_lock(&this->mutex_);
    // 初始化化event loop，之后通知主线程
    // this->loop_ = new EventLoop(this->thread_name_);
    // yolanda_msgx("event loop thread init and signal, %s", eventLoopThread->thread_name);
    // pthread_cond_signal(&this->cond_);
    // pthread_mutex_unlock(&this->mutex_);
    // this->loop->run();
    // event_loop_run(eventLoopThread->eventLoop);
}

#endif